package com.xiao.mp3;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.farng.mp3.MP3File;
import org.farng.mp3.TagConstant;
import org.farng.mp3.TagOptionSingleton;
import org.farng.mp3.id3.AbstractID3v2;
import org.farng.mp3.id3.ID3v1;

import com.xiao.mp3.util.LoadProperties;

public class ModifyFile {

	private static String srcFilePath = LoadProperties.getProperties()
			.getProperty("srcFilePath");
	private static String targetFilePath = LoadProperties.getProperties()
			.getProperty("targetFilePath");

	public static void main(String[] args) {
		ModifyFile mf = new ModifyFile();
		List<String> list = mf.getFileList(srcFilePath);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(sdf.format(new Date())+": begin ");
		long start = new Date().getTime();
		int count =0;
		for (String s : list) {
			count++;
			File sourceFile = new File(s);
			String exName = mf.getFileExtendsName(s);
			String newName = mf.getGenerateShortUuid();
			File targetFile = new File(targetFilePath + File.separator
					+ newName + exName);
			if (targetFile.exists()) {
				newName = mf.getGenerateShortUuid();
				targetFile = new File(targetFilePath + File.separator + newName
						+ exName);
			}
				System.out.println(count+"--"+sdf.format(new Date())+":"+sourceFile+"->"+targetFile);
				mf.fileChannelCopy(sourceFile, targetFile);
//				mf.modifyMp3(targetFilePath + File.separator+newName+ exName);
		}
		long end = new Date().getTime();
		System.out.println(sdf.format(new Date())+": end ");
		System.out.println("total time : "+(end-start)/1000+"s,total num:"+count);
	}
	
	public String getFileExtendsName(String srcFile){
		String str[] = srcFile.split("\\.");
		String s = str[str.length-1];
		return "."+s;
	}
	/**
	 * 重命名
	 * 
	 * @param oldFile
	 * @param newName
	 */
	public void reNameFile(File oldFile, String newName) {
		System.out.println("修改前文件名称是：" + oldFile.getName());
		String rootPath = oldFile.getParent();
		System.out.println("根路径是：" + rootPath);
		File newFile = new File(rootPath + File.separator + newName);
		System.out.println("修改后文件名称是：" + newFile.getName());
		if (oldFile.renameTo(newFile)) {
			System.out.println("修改成功!");
		} else {
			System.out.println("修改失败");
		}
	}

	private static Map<String, String> map = new HashMap<String, String>();

	public Map<String, String> getFileMap(String srcFilePath) {

		File dir = new File(srcFilePath);
		File[] files = dir.listFiles();
		if (files == null)
			return null;

		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				getFileMap(files[i].getAbsolutePath());
			} else {
				String fileName = files[i].getName();
				String filePath = files[i].getPath();

				System.out.println("fileName-------" + fileName);
				System.out.println("filePath-------" + filePath);
				map.put(files[i].getAbsolutePath(), filePath + "," + fileName);
			}
		}
		return map;
	}

	private static List<String> filelist = new ArrayList<String>();

	public List<String> getFileList(String srcFilePath) {

		File dir = new File(srcFilePath);
		File[] files = dir.listFiles();
		if (files == null)
			return null;

		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				getFileList(files[i].getAbsolutePath());
			} else {
				String fileName = files[i].getName();
				String filePath = files[i].getPath();

				System.out.println("fileName-------" + fileName);
				System.out.println("filePath-------" + filePath);

				filelist.add(files[i].getAbsolutePath());
			}
		}
		return filelist;
	}

	// 复制文件
	public void copyFile(File sourceFile, File targetFile) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
		}
	}

	public void fileChannelCopy(File sourceFile, File targetFile) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(sourceFile);
			fo = new FileOutputStream(targetFile);
			in = fi.getChannel();// 得到对应的文件通道
			out = fo.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fi.close();
				in.close();
				fo.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
			"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
			"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9" };

	// public static String[] chars = new String[] { "a", "b", "c", "d", "e",
	// "f",
	// "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
	// "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
	// "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
	// "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
	// "W", "X", "Y", "Z" };

	public String getGenerateShortUuid() {
		StringBuffer shortBuffer = new StringBuffer();
		String uuid = UUID.randomUUID().toString().replace("-", "");
//		for (int i = 0; i < 10; i++) {
//			String str = uuid.substring(i * 4, i * 4 + 4);
//			int x = Integer.parseInt(str, 16);
//			shortBuffer.append(chars[x % 0x24]);
//		}
//		return shortBuffer.toString();
		return uuid;

	}
	
	public void modifyMp3(String filePath){
		try {
			File sourceFile = new File(filePath);
			MP3File mp3file = new MP3File(sourceFile);
			ID3v1 v1 = mp3file.getID3v1Tag();
//			ID3v2_3 v2 = (ID3v2_3) mp3file.getID3v2Tag();
//			ID3v1_1 tagID3v1_1 = new ID3v1_1(mp3file);
//		    ID3v1 tagID3v1 = new ID3v1(mp3file);
//		    ID3v2_4 tagID3v2_4 = new ID3v2_4(mp3file);
//		    ID3v2_3 tagID3v2_3 = new ID3v2_3(mp3file);
//		    ID3v2_2 tagID3v2_2 = new ID3v2_2(mp3file);
//		    Lyrics3v2 tagLyrics3v2 = new Lyrics3v2(mp3file);
//		    Lyrics3v1 tagLyrics3v1 = new Lyrics3v1(mp3file);
			AbstractID3v2 id3v2 = mp3file.getID3v2Tag();  
			ID3v1 id3v1 = mp3file.getID3v1Tag();  
			
            if (id3v2 != null) {  
            	TagOptionSingleton.getInstance().setDefaultSaveMode(  
                        TagConstant.MP3_FILE_SAVE_OVERWRITE);
            	
                System.out.println("id3v2");  
                System.out.println(id3v2.getAlbumTitle());//专辑名  
                System.out.println(id3v2.getSongTitle());//歌曲名  
//                System.out.println((new String(id3v2.getSongTitle().getBytes("utf-16"),"ISO-8859-1")));//歌曲名  
                System.out.println(id3v2.getLeadArtist());//歌手  
                id3v2.setSongTitle( "");
                id3v2.setAlbumTitle( "");
                id3v2.setLeadArtist( "");
                id3v2.setSongComment( "");
                mp3file.setID3v2Tag(id3v2);
                TagOptionSingleton.getInstance().setFilenameTagSave(true);
                mp3file.save();
            } else {  
                System.out.println("id3v1");  
                System.out.println(id3v1.getAlbumTitle());  
                System.out.println(id3v1.getSongTitle());  
                System.out.println(id3v1.getLeadArtist());  
  
            }  
		} catch (Exception e) {
			System.out.println("modify mp3 error");
			e.printStackTrace();
		}
	}
}
